﻿using System;
using System.Data;
using System.Net.Mail;
using System.Net.Sockets;
using System.Collections;
using System.Text;
using System.Web;
using Base;
using System.Data.SqlClient;
using nspEmail;
using WebBasicInfo;

namespace nspBase.Core
{

    /// <summary>
    /// 邮件发送类 
    /// </summary>
    public class clsEmail
    {
        /// <summary>
        ///  获取xml配置文件信息
        /// </summary>
        /// <param name="strTo">收件人地址(可以是多个地址用"|"隔开)</param>
        /// <param name="strType">邮件类型</param>
        /// <param name="strIsHTML">是否是HTML邮件</param>
        public static string SendMail(string strTo, string strType, bool strIsHTML)
        {
            XMLProcess strXML = new XMLProcess("xml/common.config");
            string strfrom = strXML.Read("/configuration/config/copemail/emailaddress");
            string strpass = strXML.Read("/configuration/config/copemail/emailpass");
            string strsmtp = strXML.Read("/configuration/config/copemail/emailsmtp");
            string strTitle = strXML.Read("/configuration/email/emailmode[@type='" + strType + "']/title");
            string strBody = strXML.Read("/configuration/email/emailmode[@type='" + strType + "']/body");
            string strwebname = strXML.Read("/configuration/config/webname");
            return SendMail(strTo, strTitle, strBody, strIsHTML);
        }
        /// <summary>
        ///  获取邮件模版信息
        /// </summary>
        /// <param name="strType">邮件标志</param>
        /// <param name="strTO">收件人邮箱</param>
        public static string SendMail(string strType, string strTo)
        {
            bool strIsHTML = false;
            string strWhere = "where 1=1 and Flag='" + strType + "'";
            DataTable strData = new DataTable();
            EmailTemplate email = new EmailTemplate();
            DataTable dt = email.GetDataTable(strWhere);
            string strTitle = dt.Rows[0]["Title"].ToString();
            string strBody = dt.Rows[0]["Content"].ToString();
            if (dt.Rows[0]["isHtml"].ToString() != "")
                strIsHTML = Convert.ToBoolean(dt.Rows[0]["isHtml"].ToString());
            else
                strIsHTML = false;
            return SendMail(strTo, strTitle, strBody, strIsHTML);
        }
        /// <summary>
        ///  获取邮件模版信息
        /// </summary>
        /// <param name="strType">邮件标志</param>
        /// <param name="strTO">收件人邮箱</param>
        /// <param name="strBody">邮件内容</param>
        public static string SendMail(string strTitle, string strTo,string strBody)
        {
            bool strIsHTML = true;       
            return SendMail(strTo, strTitle, strBody, strIsHTML);
        }
        /// <summary>
        /// 获取发送人的邮箱信息
        /// </summary>
        /// <param name="strTo">发送的邮箱地址</param>
        /// <param name="strTitle">发送邮件标题</param>
        /// <param name="strBody">发送邮件内容</param>
        /// <param name="strIsHTML">是否是HTML邮件 </param>
        /// <returns></returns>
        public static string SendMail(string strTo, string strTitle, string strBody, bool strIsHTML)
        {
            System.Threading.Thread.Sleep(200);
            IWebBasicInfo strBasic = new RWebBasicInfo();
            TWebBasicInfo Info = strBasic.GateItem();
            string strFrom = Info.Email;
            string strLoginName = Info.EmailName;
            string strPass = Info.EmailPass;
            string strSMTP =Info.SMTP;//"smtp.163.com";
            return SendMail(strTo, strTitle, strBody, strIsHTML, strFrom, strLoginName, strPass, strSMTP,"");
        }

        /// <summary>
        ///  获取要发送人的邮箱信息及收件人的邮箱地址
        /// </summary>
        /// <param name="strType">邮件标志</param>
        /// <param name="UserID">会员ID</param>
        public static string SendMail(string strType, int UserID)
        {
            DataTable strData = new DataTable();
            if (strType != null && strType != "")
            {
                strData = Solely.Other.GetEmailValue(strType, UserID);
            }
            string strBody = "";
            string strTo = strData.Rows[0]["strTo"].ToString();
            string strLoginName = strData.Rows[0]["strLoginName"].ToString();
            string strpass = strData.Rows[0]["strPassWord"].ToString();
            string strsmtp = strData.Rows[0]["strSMTP"].ToString();
            string strTitle = strData.Rows[0]["strTitle"].ToString();
            string strFlag = Base.XMLProcess.Read("xml/EmailFlag.xml", "/Item/flag/mode[@type='userFindPwd']", "value");
            if (strFlag == strType)
                strBody = "请点击<a href='" + Base.BasePage.Config.WebURL + "login/FindPwd.aspx?UserID=" + UserID + "'>这里</a>找回密码";
            else
                strBody = strData.Rows[0]["strInfo"].ToString();
            bool strIsHTML = false;
            if (strData.Rows[0]["strIsHTML"].ToString()!="")
                strIsHTML = Convert.ToBoolean(strData.Rows[0]["strIsHTML"].ToString());
            string strFrom = strData.Rows[0]["strFrom"].ToString();
            return SendMail(strTo, strTitle, strBody, strIsHTML, strFrom, strLoginName, strpass, strsmtp);
        }
        /// <summary>
        /// 单封邮件发送
        /// </summary>
        /// <param name="strTo">收件人地址(可以是多个地址用"|"/","/";"隔开)</param>
        /// <param name="strTitle">邮件标题</param>
        /// <param name="strBody">邮件内容</param>
        /// <param name="strIsHTML">是否是HTML邮件</param>
        /// <param name="strFrom">发件人地址</param>
        /// <param name="strLoginName">发件人名称</param>
        /// <param name="strPassword">发件人邮箱密码</param>
        /// <param name="strSMTP">发件人SMTP</param>
        /// <returns></returns>
        public static string SendMail(string strTo, string strTitle, string strBody, bool strIsHTML, string strFrom, string strLoginName, string strPassword, string strSMTP)
        {
            System.Threading.Thread.Sleep(500);
            string[] str = strTo.Split(new char[] { ',', ';', '|' });
            string strCount = "";
            for (int i = 0; i < str.Length; i++)
            {

                if (!Base.Common.isMail(str[i]))
                {
                    strCount = "收件人邮箱格式不正确";
                    return strCount;
                }
                if (!Base.Common.isMail(strFrom))
                {
                    strCount = "发件人邮箱格式不正确";
                    return strCount;
                }
                MailMessage msg = new MailMessage();
                msg.From = new MailAddress(strFrom, strLoginName, System.Text.Encoding.UTF8);
                /* 上面3个参数分别是发件人地址，发件人姓名，编码*/
                msg.Subject = strTitle;                           //邮件标题 
                msg.SubjectEncoding = System.Text.Encoding.UTF8;  //邮件标题编码 
                msg.Body = strBody;                               //邮件内容 
                msg.BodyEncoding = System.Text.Encoding.UTF8;     //邮件内容编码 
                msg.IsBodyHtml = strIsHTML;                       //是否是HTML邮件 
                msg.Priority = MailPriority.High;               //邮件优先级 Normal
                SmtpClient client = new SmtpClient();
                client.Credentials = new System.Net.NetworkCredential(strFrom, strPassword);
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.Host = strSMTP;
                object userState = msg;
                msg.To.Add(str[i].ToString());

                try
                {
                    System.Threading.Thread.Sleep(100);
                    client.Send(msg);
                    strCount = "发送成功";
                }
                catch (SmtpException ex)
                {
                    strCount = "发送失败";
                }
            }
            return strCount;
        }
        /// <summary>
        /// 群发邮件
        /// </summary>
        /// <param name="strTo">收件人地址(可以是多个地址用"|"/","/";"隔开)</param>
        /// <param name="strTitle">邮件标题</param>
        /// <param name="strBody">邮件内容</param>
        /// <param name="strIsHTML">是否是HTML邮件</param>
        /// <param name="strFrom">发件人地址</param>
        /// <param name="strLoginName">发件人名称</param>
        /// <param name="strPassword">发件人邮箱密码</param>
        /// <param name="strSMTP">发件人SMTP</param>
        /// <returns></returns>
        public static string SendMail(string strTo, string strTitle, string strBody, bool strIsHTML, string strFrom, string strLoginName, string strPassword, string strSMTP, string strFree)
        {
            string[] str = strTo.Split(new char[] { ',', ';', '|' });
            string strCount = "";
            MailMessage msg = new MailMessage();
            msg.From = new MailAddress(strFrom, strLoginName, System.Text.Encoding.UTF8);
            /* 上面3个参数分别是发件人地址，发件人姓名，编码*/
            msg.Subject = strTitle;                           //邮件标题 
            msg.SubjectEncoding = System.Text.Encoding.UTF8;  //邮件标题编码 
            msg.Body = strBody;                               //邮件内容 
            msg.BodyEncoding = System.Text.Encoding.UTF8;     //邮件内容编码 
            msg.IsBodyHtml = strIsHTML;                       //是否是HTML邮件 
            msg.Priority = MailPriority.High;               //邮件优先级 
            SmtpClient client = new SmtpClient();
            client.Credentials = new System.Net.NetworkCredential(strFrom, strPassword);
            client.Host = strSMTP;
            client.DeliveryMethod=SmtpDeliveryMethod.Network;
            object userState = msg;
            for (int i = 0; i < str.Length; i++)
            {
                if (!Base.Common.isMail(str[i]))
                {
                    strCount = "收件人邮箱格式不正确";
                    return strCount;
                }
                if (!Base.Common.isMail(strFrom))
                {
                    strCount = "发件人邮箱格式不正确";
                    return strCount;
                }
                msg.To.Add(str[i].ToString());
            }
            try
            {
                System.Threading.Thread.Sleep(200);
                client.Send(msg);
                strCount = "发送成功";
            }
            catch (SmtpException ex)
            {
                strCount = "发送失败";
            }
            return strCount;
        }       
    }
}
